package com.cx.base.day13_io.io_05_objectStream;

import java.io.*;
import java.util.Iterator;

/**
 * @Author: robert.song
 * @Date: Created in 2022/4/23
 */
public class ObjectStream {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        objectWrite2Read();
    }

    private static void objectWrite2Read() throws IOException, ClassNotFoundException {
        Object p1 = new Person("一辉", 25);
        Object p2 = new String("一辉");
        File file = objectWrite(p1, p2);
        objectRead(file);
    }

    private static File objectWrite(Object... objects) throws IOException {

        ObjectOutputStream oos = null;
        File file = null;
        try {
            //自定义一个文件格式
            file = new File("object.object");
            oos = new ObjectOutputStream(new FileOutputStream(file));
            for (Object object : objects) {
                oos.writeObject(object);
                oos.flush();
            }
            return file;
        } finally {
            if (oos != null) {
                oos.close();
            }
        }

    }

    private static void objectRead(File file) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = null;
        ois = new ObjectInputStream(new FileInputStream(file));
        try {
            while (true) {
                try {
                    Object o = ois.readObject();
                    System.out.println(o);
                } catch (EOFException e) {
                    break;
                } catch (NullPointerException e) {
                    continue;
                }
            }
        } finally {
            ois.close();
        }
    }
}
